package yu.vert.main;

import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;
import io.vertx.core.net.NetSocket;
import yu.vert.vertice.MyVerticle;

public class VertMain {

    public static void main(String[] args) {

        Vertx vertx = Vertx.factory.vertx(new VertxOptions().setWorkerPoolSize(40));
        createNetServer(vertx);
        //createNetClient(vertx);
    }

    /**
     * 周期执行
     * @param vertx
     */
    public static void periodic(Vertx vertx) {
        vertx.setPeriodic(1000, id -> {
            System.out.println("111");
        });
    }

    /**
     * 执行同步代码块
     * @param vertx
     */
    public static void executeBlocking(Vertx vertx) {
        vertx.executeBlocking(future -> {
            String result = "result aaa";
            future.complete(result);
        }, res -> {
            System.out.println("result" + res);
        });
    }

    public static void startMyVerticle(Vertx vertx) {
        vertx.deployVerticle(new MyVerticle(), res -> {
            if(res.succeeded()){
                System.out.println("deployment id is " + res.result());
            }else{
                System.out.println("fail");
            }
        });
        //获取java配置参数
        System.out.println(System.getenv("JAVA_HOME"));
    }

    public static void jsonObject() {
        String jsonStr = "{\"a\":\"b\"}";
        JsonObject jsonObject = new JsonObject(jsonStr);
        jsonObject.put("c","d");
        jsonObject.getString("c");
    }

    public static void createNetServer(Vertx vertx) {
        NetServer netServer = vertx.createNetServer();
        netServer.connectHandler(socket -> {
            socket.handler(buffer -> {
                System.out.println("some bytes" + buffer.length());
                System.out.println(buffer.toString());
            });
        });
        netServer.listen(8081, "localhost", res -> {
            if(res.succeeded()){
                System.out.println("createNetServer success");
            }
        });
    }

    public static void createNetClient(Vertx vertx) {

        NetClient client = vertx.createNetClient();
        client.connect(8081, "localhost" , res -> {
            if(res.succeeded()){
                System.out.println("Connected!");
                NetSocket socket = res.result();
                System.out.println(socket);
            }
        });
    }

    public static void createHttpServer(Vertx vertx) {

        vertx.createHttpServer();

    }
}
